home *** CD-ROM | disk | FTP | other *** search
/ Ian & Stuart's Australian Mac: Not for Sale / Another.not.for.sale (Australia).iso / Dr. Doyle / C Lesson / C-LESSON.8 < prev    next >
Text File  |  1993-11-03  |  19KB  |  503 lines

  1.  
  2.                                      Lesson 7.
  3.  
  4.                              De-bugging Strategies.
  5.  
  6.       >>>>>>>> Proper Preparation Prevents Piss-Poor Performance. <<<<<<<<
  7.  
  8.   This lesson is really a essay about how to go about writing programs.
  9.  
  10.   I know that by far the best way to greatly reduce the amount of effort
  11. required to get a program going properly is to avoid making mistakes in the
  12. first palace! Now this might seem to be stating the absolute obvious, and it
  13. is but after looking at many programs it would seem that there is a very
  14. definite need to say it.
  15.  
  16.   So how does one go about reducing the probability of making mistakes?
  17.  
  18.   There are many strategies, and over the years I have evolved my own set.
  19.   I have found that some of the most important are:
  20.  
  21.   1) Document what you are going to do before yes BEFORE you write any code.
  22.      Set up the source files for the section of the program you are going to
  23.      write and put some lines of explanation as to what you intend to do in
  24.      this file. Be as precise as you can, but don't go into the detail of
  25.      explaining in English, or your First Language, exactly what every
  26.      statement does.
  27.  
  28.   2) Make sure that you keep each file as small as is sensible. Some program
  29.      authors say that one should put only one function in a file. It's my
  30.      personal opinion that this is going a little bit over the top, but
  31.      certainly you should not have more than one logical activity in a source
  32.      file. It's easier to find a needle in a tiny haystack than in a big one!
  33.  
  34.   3) Always use names for the objects in your program which are fully
  35.      descriptive, or at the very least are meaningful nmemonics. Put yourself
  36.      in the position of some poor soul who - a couple of years later, after you
  37.      have long finished with the project, and left the country - has been given
  38.      the task of adding a small feature to your exquisite program. Now in the
  39.      rush to get your masterpiece finished you decided to use variable names
  40.      like "a4" and "isb51" simply so that you can get the line typed a
  41.      fraction of a second faster than if you used something like
  42.      "customer_address[POST_CODE]" and "input_status_block[LOW_FUEL_TANK_#3].
  43.      The difference in ease of understanding is obvious, isn't it? However
  44.      judging by some programs which I have seen published in both magazines and
  45.      in the public domain program sources, the point has still to be made.
  46.  
  47.   4) ALWAYS take great care with the layout of your code.
  48.      It's my opinion that the opening brace of ALL program structures should
  49.      be on a new line. Also if you put them in the leftmost column for structs,
  50.      enums, and initialised tables, as well as functions, then the
  51.      'find function' keystrokes ( "[[" and "]]" ) in vi will find them as well
  52.      as the functions themselves. Make sure you have the "showmatch" facility
  53.      in vi turned on. ( And watch the cursor jump when you enter the
  54.      right hand brace, bracket, or parenthesis. )
  55.  
  56.   5) Try as hard as you can to have as few global variables as possible.
  57.      Some people say never have any globals. This is perhaps a bit too
  58.      severe but global variables are a clearly documented source of
  59.      programming errors. If it's impossible to perform a logical activity
  60.      in an efficient way without having a global or two, then confine
  61.      the scope of the globals to just the one file by marking the defining
  62.      declaration "static". This stops the compiler producing a symbol which
  63.      the linking loader will make available to all the files in your source.
  64.  
  65.   6) Never EVER put 'magic numbers' in you source code. Always define constants
  66.      in a header file with #define lines or enum statements.
  67.  
  68.      Here is an example:-
  69.  
  70.  
  71. /* ----------------------------------------- */
  72.  
  73. #include <stdio.h>
  74.  
  75. enum status_input_names
  76. {
  77.   radiator_temperature,
  78.   oil_temperature,
  79.   fuel_pressure,
  80.   energy_output,
  81.   revolutions_per_minute
  82.   };
  83.  
  84. char *stats[] =
  85. {
  86.   "radiator_temperature",
  87.   "oil_temperature",
  88.   "fuel_pressure",
  89.   "energy_output",
  90.   "revolutions_per_minute"
  91.   };
  92.  
  93. #define NUMBER_OF_INPUTS ( sizeof ( stats ) / sizeof ( stats[0]))
  94.  
  95. main()
  96. {
  97.   enum status_input_names name;
  98.  
  99.   printf ( "Number of Inputs is: %d\n", NUMBER_OF_INPUTS );
  100.   for ( name = radiator_temperature; name < NUMBER_OF_INPUTS; name++)
  101.   {
  102.     printf ( "\n%s", stats[ name ] );
  103.     }
  104.   printf ( "\n\n" );
  105.   }
  106.  
  107. /* ----------------------------------------- */
  108.  
  109.   Note that as a side effect we have available the meaningful symbols
  110.   radiator_temperature etc. as indices into the array of status input names
  111.   and the symbol NUMBER_OF_INPUTS available for use as a terminator in the
  112.   'for' loop. This is quite legal because sizeof is a pseudo-function and the
  113.   value is evaluated at the time of compilation and not when the program is
  114.   executed. This means that the result of the division in the macro is
  115.   calculated at the time of compilation and this result is used as a literal
  116.   in the 'for' loop. No division takes place each time the loop is executed.
  117.  
  118.   To illustrate the point I would like to tell you a little story which is
  119.   fictitious, but which has a ring of truth about it.
  120.   Your employer has just landed what seems to be a lucrative contract with
  121.   an inventor of a completely new type of engine. We are assured that after
  122.   initial proving trials one of the larger Japanese motor manufactures is
  123.   going to come across with umpteen millions to complete the development of
  124.   the design. You are told to write a program which has to be a simple and
  125.   straightforward exercise in order to do the job as cheaply as possible.
  126.   Now, the customer - a some-what impulsive type - realises that his
  127.   engine is not being monitored closely enough when it starts to rapidly
  128.   dis-assemble itself under high speed and heavy load. You have to add a
  129.   few extra parameters to the monitoring program by yesterday morning!
  130.   You just add the extra parameters into the enumand the array of pointers
  131.   to the character strings. So:
  132.  
  133. enum status_input_names
  134. { radiator_temperature,
  135.   radiator_pressure,
  136.   fuel_temperature,
  137.   fuel_pressure,
  138.   oil_temperature,
  139.   oil_pressure,
  140.   exhaust_manifold_temperature
  141.   };
  142.  
  143.   Let's continue the story about the Japanese purchase. Mr. Honda ( jun ) has
  144.   come across with the money and the result is that you are now a team leader
  145.   in the software section of Honda Software ( YourCountry ) Ltd. The project of
  146.   which you are now leader is to completely rewrite your monitoring program and
  147.   add a whole lot of extra channels as well as to make the printouts much more
  148.   readable so that your cheap, cheerful, and aesthetic-free program can be sold
  149.   as the "Ultimate Engine Monitoring Package" from the now world famous Honda
  150.   Real-time Software Systems. You set to work, Honda et. al. imagine that there
  151.   is going to be a complete redesign of the software at a cost of many million
  152.   Yen. You being an ingenious type have written the code so that it is easy to
  153.   enhance.
  154.  
  155.   The new features required are that the printouts have to be printed with the
  156.   units of measure appended to the values which have to scaled and processed so
  157.   that the number printed is a real physical value instead of the previous
  158.   arrangement where the raw transducer output was just dumped onto a screen.
  159.  
  160.   What do you have to do?
  161.  
  162.   Thinking along the line of "Get the Data arranged correctly first".
  163.   You take you old code and expand it so that all the items of information
  164.   required for each channel are collected into a struct.
  165.  
  166. enum status_input_names
  167. {
  168.   radiator_temperature,
  169.   radiator_pressure,
  170.   fuel_temperature,
  171.   fuel_pressure,
  172.   oil_temperature,
  173.   oil_pressure,
  174.   exhaust_manifold_temperature,
  175.   power_output,
  176.   torque
  177.   };
  178.  
  179. typedef struct channel
  180. {
  181.   char *name;                    /* Channel Name to be displayed on screen. */
  182.   int nx;                        /* position of name on screen x co-ordinate.
  183. */
  184.   int ny;                        /* ditto for y */
  185.   int unit_of_measure;           /* index into units of measure array */
  186.   char value;                    /* raw datum value from 8 bit ADC */
  187.   char lower_limit;              /* For alarms. */
  188.   char upper_limit;
  189.   float processed_value;         /* The number to go on screen. */
  190.   float offset;
  191.   float scale_factor;
  192.   int vx;                        /* Position of value on screen. */
  193.   int vy;
  194.   }CHANNEL;
  195.  
  196. enum units_of_measure { kPa, degC, kW, rpm, Volts, Amps, Newtons };
  197.  
  198. char *units { "kPa", "degC", "kW", "rpm", "Volts", "Amps", "Newtons" };
  199.  
  200. CHANNEL data [] =
  201. {
  202.   { "radiator temperature",
  203.   { "radiator pressure",
  204.   { "fuel temperature",
  205.   { "fuel pressure",
  206.   { "oil temperature",
  207.   { "oil pressure",
  208.   { "exhaust manifold temperature",
  209.   { "power output",
  210.   { "torque",
  211.   };
  212.  
  213. #define NUMBER_OF_INPUTS sizeof (data ) / sizeof ( data[0] )
  214.  
  215. Now the lesson preparation is to find the single little bug in the above
  216. program fragment, to finish the initialisation of the data array of type
  217. CHANNEL and to have a bit of a crack at creating a screen layout
  218. program to display its contents. Hint: Use printf();
  219. ( Leave all the values which originate from the real world as zero. )
  220.  
  221.  
  222.   Here are some more tips for young players.
  223.  
  224.   1) Don't get confused between the logical equality operator,
  225.  
  226.      ==
  227.  
  228.      and the assignment to a variable operator.
  229.  
  230.      =
  231.  
  232.      This is probably the most frequent mistake made by 'C' beginners, and
  233.      has the great disadvantage that, under most circumstances, the compiler
  234.      will quite happily accept your mistake.
  235.  
  236.   2) Make sure that you are aware of the difference between the logical
  237.      and bit operators.
  238.  
  239.      &&         This is the logical AND function.
  240.      ||         This is the logical OR function.
  241.                 The result is ALWAYS either a 0 or a 1.
  242.  
  243.      &          This is the bitwise AND function used for masks etc.
  244.                 The result is expressed in all the bits of the word.
  245.  
  246.   3) Similarly to 2 be aware of the difference between the logical
  247.      complementation and the bitwise one's complement operators.
  248.  
  249.      !          This is the logical NOT operator.
  250.      ~          This is the bitwise ones complement op.
  251.  
  252.      Some further explanation is required. In deference to machine efficiency a
  253.      LOGICAL variable is said to be true when it is non-zero. So let's set a
  254.      variable to be TRUE.
  255.  
  256.      00000000000000000000000000000001  A word representing TRUE.
  257.                                        Now let's do a logical NOT  !.
  258.      00000000000000000000000000000000  There is a all zero word, a FALSE.
  259.  
  260.      00000000000000000000000000000001  That word again. TRUE.
  261.                                        Now for a bitwise complement  ~.
  262.      11111111111111111111111111111110  Now look we've got a word which is
  263.                                        non-zero, still TRUE.
  264.  
  265.                                        Is this what you intended?
  266.  
  267.   4) It is very easy to fall into the hole of getting the
  268.      '{' & '}'; '[' & ']'; '(' & ')'; symbol pairs all messed up and the
  269.      computer thinks that the block structure is quite different from that
  270.      which you intend. Make sure that you use an editor which tells you the
  271.      matching symbol. The UNIX editor vi does this provided that you turn
  272.      on the option. Also take great care with your layout so that the block
  273.      structure is absolutely obvious, and whatever style you choose do take
  274.      care to stick by it throughout the whole of the project.
  275.      A personal layout paradigm is like this:
  276.  
  277.   Example 1.
  278.  
  279. function_type function_name ( a, b )
  280. type a;
  281. type b;
  282. {
  283.   type variable_one, variable_two;
  284.  
  285.   if ( logical_expression )
  286.   {
  287.     variable_one = A_DEFINED_CONSTANT;
  288.     if ( !return_value = some_function_or_other ( a,
  289.                                                   variable_one,
  290.                                                   &variable_two
  291.                                                   )
  292.          )
  293.     {
  294.       error ( "function_name" );
  295.       exit ( FAILURE );
  296.       }
  297.     else
  298.     {
  299.       return ( return_value + variable_two );
  300.       }
  301.     }    /* End of "if ( logical_expression )" block */
  302.   }    /* End of function */
  303.  
  304.   This layout is easy to do using vi with this initialisation script
  305.   in either the environment variable EXINIT or the file ${HOME}/.exrc:-
  306.  
  307. set showmode autoindent autowrite tabstop=2 shiftwidth=2 showmatch wm=1
  308.  
  309.   Example 2.
  310.  
  311. void printUandG()
  312. {
  313.   char *format =
  314. "\n\
  315.            User is: %s\n\
  316.           Group is: %s\n\n\
  317.  Effective User is: %s\n\
  318. Effective Group is: %s\n\n";
  319.  
  320.   ( void ) fprintf ( tty,
  321.                      format,
  322.                      passwd_p->pw_name,
  323.                      group_p->gr_name,
  324.                      epasswd_p->pw_name,
  325.                      egroup_p->gr_name
  326.                      );
  327.   }
  328.  
  329.   Notice how it is possible to split up format statements with a '\' as
  330.   the last character on the line, and that it is convenient to arrange
  331.   for a nice output format without having to count the
  332.   field widths. Note however that when using this technique that the '\'
  333.   character MUST be the VERY LAST one on the line. Not even a space may
  334.   follow it!
  335.  
  336.   In summary I *ALWAYS* put the opening brace on a new line, set the tabs
  337.   so that the indentation is just two spaces, ( use more and you very quickly
  338.   run out of "line", especially on an eighty column screen ). If a statement
  339.   is too long to fit on a line I break the line up with the arguments set out
  340.   one to a line and I then the indentation rule to the parentheses "()"
  341.   as well. Sample immediately above. Probably as a hang-over from a particular
  342.   pretty printing program which reset the indentation position after the
  343.   printing of the closing brace "}", I am in the habit of doing it as well.
  344.   Long "if" and "for" statements get broken up in the same way. This is
  345.   an example of it all. The fragment of code is taken from a curses oriented
  346.   data input function.
  347.  
  348.   /*
  349.   ** Put all the cursor positions to zero.
  350.   */
  351.  
  352.   for ( i = 0;
  353.         s[i].element_name != ( char *) NULL &&
  354.         s[i].element_value != ( char *) NULL;
  355.         i = ( s[i].dependent_function == NULL )
  356.             ? s[i].next : s[i].dependent_next
  357.         )
  358.   {                              /* Note that it is the brace and NOT the    */
  359.                                  /* "for" which moves the indentation level. */
  360.     s[i].cursor_position = 0;
  361.     }
  362.  
  363.   /*
  364.   ** Go to start of list and hop over any constants.
  365.   */
  366.  
  367.     for ( i = edit_mode = current_element = 0;
  368.           s[i].element_value == ( char *) NULL ;
  369.           current_element = i = s[i].next
  370.           ) continue;                               /* Note EMPTY statement. */
  371.  
  372.   /*
  373.   ** Loop through the elements, stopping at end of table marker,
  374.   ** which is an element with neither a pointer to an element_name nor
  375.   ** one to a element_value.
  376.   */
  377.  
  378.   while ( s[i].element_name != ( char *) NULL &&
  379.           s[i].element_value != ( char *) NULL
  380.           )
  381.   {
  382.     int c;           /* Varable which holds the character from the keyboard. */
  383.  
  384.     /*
  385.     **  Et Cetera for many lines.
  386.     */
  387.  
  388.     }
  389.  
  390.   Note the commenting style. The lefthand comments provide a general
  391. overview of what is happening and the righthand ones a more detailed view.
  392. The double stars make a good marker so it is easy to separate the code and
  393. the comments at a glance.
  394.  
  395.   The null statement.
  396.  
  397.   You should be aware that the ";" on its own is translated by the compiler
  398. as a no-operation statement. The usefullness of this is that you can do
  399. little things, such as counting up a list of objects, or positioning a pointer
  400. entirely within a "for" or "while" statement. ( See example above ).
  401. There is, as always, a flip side. It is HORRIBLY EASY to put a ";" at the
  402. end of the line after the closing right parenthesis - after all you do just
  403. that for function calls! The suggestion is to both mark deliberate null
  404. statements with a comment and to use the statement "continue;". Using
  405. the assert macro will pick up these errors at run time.
  406.  
  407.   The assert macro.
  408.  
  409.   Refer to the Programmers Reference Manual section 3X and find the
  410. documentation on this most useful tool.
  411.  
  412.   As usual an example is by far the best wasy to explain it.
  413.  
  414. /* ----------------------------------------- */
  415.  
  416. #ident "@(#) assert-demo.c"
  417.  
  418. #include <stdio.h>
  419. #include <assert.h>
  420.  
  421. #define TOP_ROW 10
  422. #define TOP_COL 10
  423.  
  424. main()
  425. {
  426.   int row, col;
  427.  
  428.   for ( row = 1; row <= TOP_ROW; row++);
  429.   {
  430.     assert ( row <= TOP_ROW );
  431.     for ( col = 1; col <= TOP_COL; col++ )
  432.     {
  433.       assert ( col <= TOP_COL );
  434.       printf ( "%4d", row * col );
  435.       }
  436.     printf ( "\n" );
  437.     }
  438.   }
  439.  
  440. /* ----------------------------------------- */
  441.  
  442.   Which produces the output:-
  443.  
  444. Assertion failed:  row <= TOP_ROW , file assert-demo.c, line 15
  445. ABORT instruction (core dumped)
  446.  
  447.   It does this because the varable "row" is incremented
  448. to one greater than The value of TOP_ROW.
  449.  
  450.   Note two things:
  451.  
  452.   1) The sense of the logical condition. The assert is asserted
  453.      as soon as the result of the logical condition is FALSE.
  454.      Have a look at the file /usr/include/assert.
  455.      Where is the ";" being used as an empty program statement?
  456.  
  457.   2) The unix operating system has dumped out an image of the executing
  458.      program for examination using a symbolic debugger. Have a play with
  459.      "sdb" in preparation for the lesson which deals with it in more
  460.      detail.
  461.  
  462.   Lets remove the errant semi-colon, re-compile and re-run the program.
  463.  
  464.    1   2   3   4   5   6   7   8   9  10
  465.    2   4   6   8  10  12  14  16  18  20
  466.    3   6   9  12  15  18  21  24  27  30
  467.    4   8  12  16  20  24  28  32  36  40
  468.    5  10  15  20  25  30  35  40  45  50
  469.    6  12  18  24  30  36  42  48  54  60
  470.    7  14  21  28  35  42  49  56  63  70
  471.    8  16  24  32  40  48  56  64  72  80
  472.    9  18  27  36  45  54  63  72  81  90
  473.   10  20  30  40  50  60  70  80  90 100
  474.  
  475.   Here's the ten times multiplication table, for you to give to to
  476. the nearest primary-school child!
  477.  
  478.   I would agree that it is not possible to compare the value of a program
  479. layout with a real work of fine art such as a John Constable painting or
  480. a Michaelangelo statue, I do think a well laid out and literate example of
  481. programming is not only much easier to read and understand, but also it
  482. does have a certain aesthetic appeal.
  483.  
  484. Copyright notice:-
  485.  
  486. (c) 1993 Christopher Sawtell.
  487.  
  488. I assert the right to be known as the author, and owner of the
  489. intellectual property rights of all the files in this material,
  490. except for the quoted examples which have their individual
  491. copyright notices. Permission is granted for onward copying,
  492. but not modification, of this course and its use for personal
  493. study only, provided all the copyright notices are left in the
  494. text and are printed in full on any subsequent paper reproduction.
  495.  
  496. --
  497.  +----------------------------------------------------------------------+
  498.  | NAME   Christopher Sawtell                                           |
  499.  | SMAIL  215 Ollivier's Road, Linwood, Christchurch, 8001. New Zealand.|
  500.  | EMAIL  chris@gerty.equinox.gen.nz                                    |
  501.  | PHONE  +64-3-389-3200   ( gmt +13 - your discretion is requested )   |
  502.  +----------------------------------------------------------------------+
  503.